<?php
namespace Libs;

/**
 * 提醒类, 支持多语言 
 * 配合 Response::obj() 使用
 * 需要配置多语言文件/数据库, 数据举例:
 * [code:10001, zh-CN:'参数不全', en-US:'missing some params']
 */
class Notice
{
    //提醒数据的缓存
    private static $cacheNotice = [];
    
    private function __construct(){}

    public static function setData($data, $lang='zh-CN')
    {
        //获取所有提醒信息
        if (empty(self::$cacheNotice)) {
            self::$cacheNotice = array_column([], $lang, 'code');
        }
        return self::class;
    }
    
    //成功时返回数据
    public static function success($data=[])
    {
        $rs = new \stdClass();
        $rs->code = 1;
        $rs->msg = '';
        $rs->error_code = 0;
        $rs->is_error = false;
        $rs->is_success = true;
        $rs->data = $data;
        return $rs;
    }
    
    /**
     * 发生错误时返回
     * @param string $code 错误码
     * @param array $params 用于替换占位符
     * @param string $extraMsg 额外消息(调用第三方接口时返回的错误信息)
     * @param array $data 备用
     * @return \stdClass
     */
    public static function error($code, $params=[], $extraMsg='', $data=null) 
    {
        //组装消息体
        $rs = new \stdClass();
        $rs->code = -1;
        $rs->msg = '';
        $rs->error_code = $code;
        $rs->is_error = true;
        $rs->is_success = false;
        $rs->data = $data;
        
        //替换占位符
        if (is_numeric($code) && isset(self::$cacheNotice[$code])) {
            $content = self::$cacheNotice[$code];
            foreach ($params as $k => $v) {
                if (!empty($v)) {
                    $content = str_replace('{'.$k.'}', (string)$v, $content); //替换占位符
                }
            }
            $rs->msg = $content;
        } else {
            $rs->msg = $code;
        }
        
        //附加额外信息
        !empty($extraMsg) && $rs->msg .= " $extraMsg";
        
        return $rs;
    }
}